package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReserveBook extends MenuList {
    String menuName = "Reserve BooK";
    BookData bookData = new BookData();
    int bookId;

    public boolean execute() throws IOException {
        File logFile = new File("src/com/twu/biblioteca/current.txt");
        BufferedReader fileReader = new BufferedReader(new FileReader(logFile));
        InputHandler inputHandler = new InputHandler();
        String dataLine;

        // consider single user per app execution
        int verifier = 0;
        while((dataLine = fileReader.readLine())!=null) {
            verifier++;
        }

        if(verifier > 0) {
            System.out.print("\nEnter Book ID to reserve: ");
            bookId = inputHandler.readOption();
            if(bookId<0 && bookId>bookData.getMaxBookId()) {
                System.out.println("Sorry! That is invalid book ID!");
            }


            bookData.readBookData();
            int bookCountInLibrary = bookData.getBookQuantity(bookId);

            if(bookCountInLibrary < 1) {
                System.out.println("Sorry! we don't have that book available.");
                return false;
            }

            bookData.putBookQuantity( bookId, bookCountInLibrary - 1);
            bookData.writeBookData();

            System.out.println("Thank You! Enjoy the book.");
            return true;
        }
        return false;
    }

    public String getMenuName() {
        return menuName;
    }

}
